package cn.edu.neusoft.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class ImageDownloader {
    // 基础路径配置
    private static final String LOCAL_BASE_PATH = "/www/wwwroot/172.17.19.229_80/static/pic";
    private static final String URL_BASE_PATH = "http://172.17.19.229/static/pic";

    /**
     * 公开入口方法：处理完整流程（下载图片+返回新URL）
     * @param imageUrl 原始图片URL
     * @return 生成的新URL
     * @throws IOException 处理异常时抛出
     */
    public static String processImage(String imageUrl) throws IOException {
        return processImage(imageUrl, false);
    }

    /**
     * 公开入口方法：处理完整流程（下载图片+返回新URL）
     * @param imageUrl 原始图片URL
     * @param enableLogging 是否启用日志输出
     * @return 生成的新URL
     * @throws IOException 处理异常时抛出
     */
    public static String processImage(String imageUrl, boolean enableLogging) throws IOException {
        SSLUtils.disableCertificateValidation();
        // System.out.println("=== [ImageDownloader] Starting image processing ===");
        // System.out.println("[DEBUG] Original URL: " + imageUrl);

        try {
            // 生成新URL
            String newUrl = generateNewUrl(imageUrl);
            if (enableLogging) {
                System.out.println("[INFO] Final new URL: " + newUrl);
            }

            // 构建本地路径
            String localPath = buildLocalPath(newUrl);
            if (enableLogging) {
                System.out.println("[INFO] Local storage path: " + localPath);
            }

            // 下载文件
            // System.out.println("[DEBUG] Starting image download...");
            // System.out.println("  Source URL: " + imageUrl);
            // System.out.println("  Target path: " + localPath);
            
            downloadImage(imageUrl, localPath);
            // System.out.println("[SUCCESS] Image download completed");
            // System.out.println("=== [ImageDownloader] Processing completed ===");
            
            return newUrl;
        } catch (Exception e) {
            System.err.println("[ERROR] Image processing failed: " + e.getMessage());
            System.err.println("[ERROR] Original URL: " + imageUrl);
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 生成新的URL地址（核心逻辑）
     */
    private static String generateNewUrl(String imageUrl) {
        // System.out.println("[DEBUG] === URL transformation started ===");
        
        // 1. 尝试提取fileUrl参数
        String targetUrl = null;
        if (imageUrl.contains("?")) {
            // System.out.println("[DEBUG] Query parameters detected, extracting fileUrl");
            String[] parts = imageUrl.split("\\?", 2);
            String query = parts[1];
            // System.out.println("[DEBUG] Query string: " + query);
            
            for (String param : query.split("&")) {
                String[] kv = param.split("=", 2);
                if ("fileUrl".equals(kv[0]) && kv.length > 1) {
                    try {
                        // 解码URL编码字符（如%2F → /）
                        targetUrl = java.net.URLDecoder.decode(kv[1], "UTF-8");
                        // System.out.println("[DEBUG] Found fileUrl parameter: " + targetUrl);
                    } catch (UnsupportedEncodingException e) {
                        targetUrl = kv[1]; // 回退未解码值
                        // System.out.println("[DEBUG] URL decode failed, using raw value: " + targetUrl);
                    }
                    break;
                }
            }
        }

        // 2. 确定要处理的URL
        String processingUrl = (targetUrl != null) ? targetUrl : imageUrl;
        // System.out.println("[DEBUG] URL to process: " + processingUrl);

        // 3. 清理URL（移除所有查询参数）
        String cleanUrl = processingUrl.split("\\?")[0];
        // System.out.println("[DEBUG] Cleaned URL: " + cleanUrl);

        // 4. 分割并过滤路径段
        List<String> validSegments = new ArrayList<>();
        String[] segments = cleanUrl.split("/");
        // System.out.println("[DEBUG] Original path segments count: " + segments.length);
        
        for (int i = 0; i < segments.length; i++) {
            String seg = segments[i];
            // System.out.println("[DEBUG] Path segment[" + i + "]: '" + seg + "'");
            if (!seg.isEmpty() && !seg.contains(":")) {
                validSegments.add(seg);
                // System.out.println("[DEBUG] Valid path segment: '" + seg + "'");
            }
        }
        
        // System.out.println("[DEBUG] Valid path segments total: " + validSegments.size());
        // for (int i = 0; i < validSegments.size(); i++) {
        //     System.out.println("[DEBUG] Valid segment[" + i + "]: '" + validSegments.get(i) + "'");
        // }

        // 5. 定位日期目录
        int dateIndex = -1;
        for (int i = 0; i < validSegments.size(); i++) {
            String seg = validSegments.get(i);
            if (seg.matches("\\d{8}")) { // 匹配8位数字格式日期
                dateIndex = i;
                // System.out.println("[DEBUG] Found date directory: '" + seg + "' at index " + i);
                break;
            }
        }
        
        if (dateIndex == -1) {
            System.err.println("[ERROR] Date directory not found!");
            System.err.println("[ERROR] Valid path segments: " + validSegments);
            throw new IllegalArgumentException("Date directory missing in URL: " + imageUrl);
        }

        // 6. 构建新路径（跳过dateIndex+1）
        StringBuilder pathBuilder = new StringBuilder(validSegments.get(dateIndex));
        // System.out.println("[DEBUG] Building new path, date directory: " + validSegments.get(dateIndex));
        
        for (int i = dateIndex + 2; i < validSegments.size(); i++) {
            pathBuilder.append("/").append(validSegments.get(i));
            // System.out.println("[DEBUG] Adding path segment[" + i + "]: " + validSegments.get(i));
        }

        String finalPath = pathBuilder.toString();
        String newUrl = URL_BASE_PATH + "/" + finalPath;
        
        // System.out.println("[DEBUG] Built relative path: " + finalPath);
        // System.out.println("[DEBUG] Final new URL: " + newUrl);
        // System.out.println("[DEBUG] === URL transformation completed ===");
        
        return newUrl;
    }

    /**
     * 查找日期目录位置
     */
    private static int findDateIndex(List<String> segments) {
        for (int i = 0; i < segments.size(); i++) {
            if (segments.get(i).matches("\\d{8}")) {
                return i;
            }
        }
        return -1;
    }

    /**
     * 根据新URL生成本地存储路径
     */
    private static String buildLocalPath(String newUrl) {
        String relativePath = newUrl.replace(URL_BASE_PATH, "");
        String localPath = LOCAL_BASE_PATH + relativePath;
        // System.out.println("[DEBUG] URL_BASE_PATH: " + URL_BASE_PATH);
        // System.out.println("[DEBUG] LOCAL_BASE_PATH: " + LOCAL_BASE_PATH);
        // System.out.println("[DEBUG] Relative path: " + relativePath);
        // System.out.println("[DEBUG] Local path: " + localPath);
        return localPath;
    }

    /**
     * 图片下载方法（增强版）
     */
    public static void downloadImage(String urlString, String destinationPath) throws IOException {
        // System.out.println("[DEBUG] === Starting image download ===");
        // System.out.println("[DEBUG] Download URL: " + urlString);
        // System.out.println("[DEBUG] Target path: " + destinationPath);
        
        // 创建目录结构
        File outputFile = new File(destinationPath);
        File parentDir = outputFile.getParentFile();
        // System.out.println("[DEBUG] Parent directory: " + parentDir.getAbsolutePath());
        // System.out.println("[DEBUG] Parent directory exists: " + parentDir.exists());
        
        if (!parentDir.exists()) {
            // System.out.println("[DEBUG] Creating directory structure...");
            boolean mkdirResult = parentDir.mkdirs();
            // System.out.println("[DEBUG] Directory creation result: " + mkdirResult);
            if (!mkdirResult) {
                System.err.println("[ERROR] Failed to create directory: " + parentDir.getAbsolutePath());
                throw new IOException("Failed to create directory: " + parentDir.getAbsolutePath());
            }
        }

        // 建立HTTP连接
        // System.out.println("[DEBUG] Establishing HTTP connection...");
        HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) new URL(urlString).openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(10000); // 10秒连接超时
            connection.setReadTimeout(30000); // 30秒读取超时
            
            // System.out.println("[DEBUG] Connection timeout: 10 seconds");
            // System.out.println("[DEBUG] Read timeout: 30 seconds");
            
            // 验证响应状态
            int responseCode = connection.getResponseCode();
            // System.out.println("[DEBUG] HTTP response code: " + responseCode);
            
            if (responseCode != HttpURLConnection.HTTP_OK) {
                System.err.println("[ERROR] HTTP request failed!");
                System.err.println("[ERROR] Response code: " + responseCode);
                System.err.println("[ERROR] Response message: " + connection.getResponseMessage());
                throw new IOException("Server response error, status code: " + responseCode + ", message: " + connection.getResponseMessage());
            }

            // 获取文件大小
            long contentLength = connection.getContentLengthLong();
            // System.out.println("[DEBUG] Content length: " + (contentLength > 0 ? contentLength + " bytes" : "unknown"));

            // 使用try-with-resources自动关闭流
            try (InputStream input = new BufferedInputStream(connection.getInputStream());
                 OutputStream output = new BufferedOutputStream(new FileOutputStream(outputFile))) {

                // System.out.println("[DEBUG] Starting to read file stream...");
                byte[] buffer = new byte[4096];
                int bytesRead;
                long totalBytesRead = 0;
                
                while ((bytesRead = input.read(buffer)) != -1) {
                    output.write(buffer, 0, bytesRead);
                    totalBytesRead += bytesRead;
                }
                
                // System.out.println("[DEBUG] File download completed, total bytes read: " + totalBytesRead);
                // System.out.println("[DEBUG] File saved to: " + outputFile.getAbsolutePath());
                // System.out.println("[DEBUG] File exists: " + outputFile.exists());
                // System.out.println("[DEBUG] File size: " + outputFile.length() + " bytes");
                
            } catch (IOException e) {
                System.err.println("[ERROR] File stream processing failed: " + e.getMessage());
                e.printStackTrace();
                throw e;
            }
        } catch (Exception e) {
            System.err.println("[ERROR] Download process exception: " + e.getMessage());
            e.printStackTrace();
            throw e;
        } finally {
            if (connection != null) {
                connection.disconnect();
                // System.out.println("[DEBUG] HTTP connection closed");
            }
        }
        
        // System.out.println("[DEBUG] === Image download completed ===");
    }

    /**
     * 示例main方法
     */
    public static void main(String[] args) {
        // SSL证书验证处理（测试环境用）
        SSLUtils.disableCertificateValidation();

        String imageUrl = "https://172.17.20.106/evo-pic/d/1000039$1$0$0/20250224/11/0205-479677-479677-0-Peccancy.jpg?oss_addr=172.17.20.106:8081";

        try {
            String newUrl = ImageDownloader.processImage(imageUrl);
            System.out.println("Processing successful! New URL: " + newUrl);

            // 实际使用示例：
            // carPeccancyDao.updateCombinedPicUrl(newUrl);
        } catch (Exception e) {
            System.err.println("Processing failed: " + e.getMessage());
            e.printStackTrace();
        }
    }
}